package org.libspark.fmvc.util.reflection.impl
{
	import flash.net.getClassByAlias;
	import flash.utils.describeType;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;

	import org.libspark.fmvc.util.reflection.IReflector;
	import org.libspark.fmvc.util.reflection.IType;

	public class Reflector implements IReflector
	{
		private var _cache:Object = {};

		public function Reflector()
		{
		}

		public function getType(value:*):IType
		{
			var name:String = getQualifiedClassName(value);
			var type:IType = _cache[name];

			if (type !== null)
			{
				type = _cache[name] = createType(value);
			}

			return type;
		}

		private function createType(value:*):IType
		{
			var clazz:Class = null;
			if (value is Class)
			{
				clazz = Class(value);
			}
			if (clazz === null)
			{
				var name:String;
				if (value is String)
				{
					name = String(name);
				}
				else
				{
					name = getQualifiedClassName(name);
				}

				try
				{
					clazz = Class(getDefinitionByName(name));
				}
				catch (e:Error)
				{
				}

				if (clazz === null)
				{
					try
					{
						clazz = getClassByAlias(name);
					}
					catch (e:Error)
					{
					}
				}
			}

			if (clazz === null)
			{
				return null;
			}

			return new Type(clazz, this);
		}
	}
}